Skip to main content

Template Generation API Integration

This comprehensive guide walks you through the Template Generation API integration process. Learn how to programmatically upload new templates or select existing ones, then generate beautiful documents with variable substitution using our RESTful API.

Template Generation API Integration Overview

Overview

The Template Generation API offers two flexible paths to document creation, because we believe in choice (and because forcing everyone down one path would be like making everyone eat vanilla ice cream forever):

Path A: Upload New Template

  1. Upload & Create - Upload your .docx/.pptx template and extract variables automatically
  2. Generate Document - Fill variables and create your deliverable

Path B: Select Existing Template

  1. Browse Templates - Explore your template library with search and filtering
  2. Template Details - Load template variables and preview PDF
  3. Generate Document - Fill variables and create your deliverable

Template Generation API Workflow

Key Features

  • RESTful API: Standard HTTP methods with JSON and multipart payloads
  • Bearer Token Authentication: Secure API access using JWT tokens
  • Dual Entry Points: Start fresh with uploads OR use existing templates
  • Smart Variable Extraction: Automatic detection of placeholders in uploaded documents
  • Rich Variable Types: Support for text, subvariables, stacks, and AI-powered content
  • Template Library: Full CRUD operations with search, filtering, and organization
  • Real-time Processing: Track document generation status throughout the process

TLDR; Complete Working Examples 🚀

Don't want to read the novel? Here's the executive summary:

Available Variable Types

TypeDescriptionExample PlaceholderUse Case
textSimple text replacement{CompanyName}Basic text substitution
subvariablesNested variable structures{Employee.FirstName}Complex hierarchical data
variableStackMultiple instances of content{Projects[0].Name}Repeating sections, lists
richTextHTML/formatted text content{Description}Formatted text with styling
aiPromptAI-generated content{Summary}Dynamic content generation

Complete Dual-Path Workflow

Loading code examples...

Quick Variable Structure Example

Here's what a complex variable payload looks like:

{
"templateId": "abc123-def456-ghi789",
"name": "Employee Contract Draft",
"description": "Generated contract for new hire",
"variables": [
{
"name": "Employee",
"placeholder": "{Employee}",
"text": "John Smith",
"subvariables": [
{
"placeholder": "{Employee.Title}",
"text": "Senior Developer"
},
{
"placeholder": "{Employee.StartDate}",
"text": "2024-01-15"
}
]
},
{
"name": "Projects",
"placeholder": "{Projects}",
"variableStack": {
"0": {
"text": "Project Alpha - Backend Development",
"subvariables": [
{
"placeholder": "{Projects.Duration}",
"text": "6 months"
}
]
},
"1": {
"text": "Project Beta - API Integration",
"subvariables": [
{
"placeholder": "{Projects.Duration}",
"text": "3 months"
}
]
}
}
}
]
}

Now let's dive into the template wizardry...

Prerequisites

Before you begin your journey into template automation nirvana, ensure you have:

  • API Access Token: Bearer token for authentication
  • Organization ID: Your organization identifier
  • Template Files: .docx or .pptx files with placeholder variables (for uploads)

Getting Your Credentials

  1. Login to TurboDocx: Visit https://www.turbodocx.com
  2. Navigate to Settings: Access your organization settings
  3. API Keys Section: Generate or retrieve your API access token
  4. Organization ID: Copy your organization ID from the settings

Template API Credentials Organization ID Location

Authentication

All Template Generation API requests require authentication using a Bearer token in the Authorization header:

Authorization: Bearer YOUR_API_TOKEN

Additional required headers for all requests:

x-rapiddocx-org-id: YOUR_ORGANIZATION_ID
User-Agent: TurboDocx API Client

Path A: Upload New Template

Start fresh by uploading a new template document. This path is perfect when you've crafted a beautiful new template and want to jump straight into document generation.

Endpoint

POST https://api.turbodocx.com/template/upload-and-create

Headers

Content-Type: multipart/form-data
Authorization: Bearer YOUR_API_TOKEN
x-rapiddocx-org-id: YOUR_ORGANIZATION_ID
User-Agent: TurboDocx API Client

Request Body (Form Data)

{
"templateFile": [DOCX_OR_PPTX_FILE_BINARY],
"name": "Employee Contract Template",
"description": "Standard employee contract with variable placeholders",
"variables": "[]", // Optional: Pre-defined variables (usually extracted automatically)
"tags": "[]" // Optional: Categorization tags
}

Response

{
"data": {
"results": {
"template": {
"name": "Employee Contract Template",
"description": "Standard employee contract with variable placeholders",
"fonts": [
{
"name": "Arial",
"usage": 269
},
{
"name": "Calibri",
"usage": 45
}
],
"defaultFont": "Arial",
"orgId": "2d66ecf0-a749-475d-9403-9956d0f67884",
"createdBy": "9d829e80-1135-4a97-93ea-cc2a1eecc9da",
"createdOn": "2025-09-19T15:45:47.000Z",
"updatedOn": "2025-09-19T15:45:47.000Z",
"isActive": 1,
"id": "31cc4cce-4ed7-4f3b-aa80-0b9a4f995412",
"variables": null,
"projectspaceId": null,
"templateFolderId": null,
"metadata": null
},
"redirectUrl": "/templates/31cc4cce-4ed7-4f3b-aa80-0b9a4f995412/generate"
}
}
}

Response Fields

FieldTypeDescription
data.results.template.idstringUnique template identifier (use for generation)
data.results.template.namestringTemplate name as provided
data.results.template.descriptionstringTemplate description
data.results.template.fontsarrayArray of font objects with name and usage
data.results.template.defaultFontstringDefault font name for the template
data.results.template.orgIdstringOrganization ID
data.results.template.createdBystringUser ID who created the template
data.results.template.createdOnstringISO timestamp of template creation
data.results.template.updatedOnstringISO timestamp of last template update
data.results.template.isActivenumberActive status (1 = active, 0 = inactive)
data.results.template.variablesarray|nullAuto-extracted variables (null if none found)
data.results.template.projectspaceIdstring|nullProject space ID (null if not assigned)
data.results.template.templateFolderIdstring|nullFolder ID (null if not in folder)
data.results.template.metadataobject|nullAdditional metadata (null if not set)
data.results.redirectUrlstringFrontend URL to redirect for variable filling

Deliverable Response Fields

FieldTypeDescription
data.results.deliverable.idstringUnique deliverable identifier
data.results.deliverable.namestringDeliverable name as provided
data.results.deliverable.createdBystringEmail of the user who created it
data.results.deliverable.createdOnstringISO timestamp of creation
data.results.deliverable.orgIdstringOrganization ID
data.results.deliverable.isActivebooleanWhether deliverable is active
data.results.deliverable.templateIdstringOriginal template ID used

Code Examples

Loading code examples...

Path B: Select Existing Template

Browse your template library to find the perfect starting point. This path lets you leverage templates you've already created and organized.

Step 1: Browse Templates

List all available templates and folders in your organization.

Endpoint

GET https://api.turbodocx.com/template-item

Headers

Authorization: Bearer YOUR_API_TOKEN
x-rapiddocx-org-id: YOUR_ORGANIZATION_ID
User-Agent: TurboDocx API Client

Query Parameters

?limit=25&offset=0&query=contract&showTags=true&selectedTags[]=tag-123
ParameterTypeDescription
limitnumberItems per page (default: 6)
offsetnumberPagination offset (default: 0)
querystringSearch term for template names
showTagsbooleanInclude tag information in response
selectedTagsarrayFilter by specific tag IDs

Response

{
"data": {
"results": [
{
"id": "0b1099cf-d7b9-41a4-822b-51b68fd4885a",
"name": "Employee / Contractor IP Agreement Example",
"description": "A Statement of Work template provided by TurboDocx",
"createdOn": "2025-05-29T19:07:16.000Z",
"updatedOn": "2025-09-08T11:44:11.000Z",
"isActive": 1,
"type": "template",
"createdBy": "9d829e80-1135-4a97-93ea-cc2a1eecc9da",
"email": "kahlerasse@gmail.com",
"templateFolderId": null,
"deliverableCount": 4,
"fileSize": 24942,
"fileType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"templateCount": 0,
"tags": []
},
{
"id": "604d1e63-6cdc-4849-9e71-548409bfec69",
"name": "Legal",
"description": null,
"createdOn": "2025-05-29T19:07:16.000Z",
"updatedOn": "2025-05-29T19:07:16.000Z",
"isActive": 1,
"type": "folder",
"createdBy": "9d829e80-1135-4a97-93ea-cc2a1eecc9da",
"email": "kahlerasse@gmail.com",
"templateFolderId": null,
"deliverableCount": 0,
"fileSize": null,
"fileType": null,
"templateCount": 0,
"tags": []
}
],
"totalRecords": 26
}
}

Browse Response Fields

FieldTypeDescription
data.results[]arrayArray of templates and folders
data.results[].idstringUnique identifier for template or folder
data.results[].namestringName of the template or folder
data.results[].descriptionstring|nullDescription (null for some items)
data.results[].createdOnstringISO timestamp of creation
data.results[].updatedOnstringISO timestamp of last update
data.results[].isActivenumberActive status (1 = active, 0 = inactive)
data.results[].typestringItem type ("template" or "folder")
data.results[].createdBystringUser ID who created the item
data.results[].emailstringEmail of the creator
data.results[].templateFolderIdstring|nullParent folder ID (null if at root level)
data.results[].deliverableCountnumberNumber of deliverables generated from template
data.results[].fileSizenumber|nullFile size in bytes (null for folders)
data.results[].fileTypestring|nullMIME type of template file (null for folders)
data.results[].templateCountnumberNumber of templates in folder (0 for templates)
data.results[].tagsarrayArray of tag objects
data.totalRecordsnumberTotal number of items available

Step 2: Get Template Details

Load specific template information including variables and metadata.

Endpoint

GET https://api.turbodocx.com/template/{templateId}

Response

{
"data": {
"results": {
"id": "0b1099cf-d7b9-41a4-822b-51b68fd4885a",
"name": "Employee Contract Template",
"description": "Standard employment agreement template",
"templateFileType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"templateFolderId": "folder-def456",
"variables": [
{
"id": "var-123",
"name": "Employee Name",
"placeholder": "{EmployeeName}",
"text": "",
"mimeType": "text",
"allowRichTextInjection": false,
"order": 1,
"subvariables": []
},
{
"id": "var-456",
"name": "Department",
"placeholder": "{Department}",
"text": "",
"mimeType": "text",
"allowRichTextInjection": true,
"order": 2,
"subvariables": [
{
"placeholder": "{Department.Manager}",
"text": ""
}
]
}
],
"fonts": [
{
"name": "Arial",
"usage": 269
}
],
"defaultFont": "Arial"
}
}
}

Step 3: Get PDF Preview (Optional)

Generate a preview PDF of the template for visual confirmation.

Endpoint

GET https://api.turbodocx.com/template/{templateId}/previewpdflink

Response

{
"results": "https://api.turbodocx.com/template/pdf/preview-abc123.pdf"
}

Code Examples

Loading code examples...

Final Step: Generate Deliverable

Both paths converge here - time to fill those variables and create your masterpiece! This is where the magic happens and placeholders become real content.

Step 1: Generate Deliverable

Endpoint

POST https://api.turbodocx.com/deliverable

Headers

Content-Type: application/json
Authorization: Bearer YOUR_API_TOKEN
x-rapiddocx-org-id: YOUR_ORGANIZATION_ID
User-Agent: TurboDocx API Client

Request Body

{
"templateId": "0b1099cf-d7b9-41a4-822b-51b68fd4885a",
"name": "Employee Contract - John Smith",
"description": "Employment contract for new senior developer",
"variables": [
{
"mimeType": "text",
"name": "Employee Name",
"placeholder": "{EmployeeName}",
"text": "John Smith",
"allowRichTextInjection": 0,
"autogenerated": false,
"count": 1,
"order": 1,
"subvariables": [
{
"placeholder": "{Employee.Title}",
"text": "Senior Software Developer"
},
{
"placeholder": "{Employee.StartDate}",
"text": "January 15, 2024"
}
],
"aiPrompt": "Generate a professional job description for a senior developer role"
},
{
"mimeType": "text",
"name": "Department",
"placeholder": "{Department}",
"text": "Engineering",
"allowRichTextInjection": 1,
"autogenerated": false,
"count": 3,
"order": 2,
"subvariables": [
{
"placeholder": "{Department.Manager}",
"text": "Sarah Johnson"
}
],
"variableStack": {
"0": {
"text": "Frontend Development Team",
"subvariables": [
{
"placeholder": "{Team.Focus}",
"text": "React and TypeScript development"
}
]
},
"1": {
"text": "Backend Development Team",
"subvariables": [
{
"placeholder": "{Team.Focus}",
"text": "Node.js and database optimization"
}
]
}
},
"metadata": {
"customField": "Engineering Department"
},
"aiPrompt": "Describe the key responsibilities of the engineering department"
}
],
"tags": ["hr-template", "contract", "full-time"],
"fonts": "[{\"name\":\"Arial\",\"usage\":269}]",
"defaultFont": "Arial",
"replaceFonts": true,
"metadata": {
"sessions": [
{
"id": "session-abc123",
"starttime": "2024-01-15T14:12:10.721Z",
"endtime": "2024-01-15T14:13:45.724Z"
}
]
}
}

Response

{
"data": {
"results": {
"deliverable": {
"id": "39697685-ca00-43b8-92b8-7722544c574f",
"name": "Employee Contract - John Smith",
"description": "Employment contract for new senior developer",
"createdBy": "api-user@company.com",
"createdOn": "2024-12-19T21:22:10.000Z",
"orgId": "your-organization-id",
"isActive": true,
"templateId": "0b1099cf-d7b9-41a4-822b-51b68fd4885a"
}
}
}
}

Variable Structure Deep Dive

Understanding the variable structure is key to successful document generation:

Basic Variable

{
"name": "Company Name",
"placeholder": "{CompanyName}",
"text": "Acme Corporation",
"mimeType": "text",
"allowRichTextInjection": false,
"order": 1
}

Variable with Subvariables

{
"name": "Employee",
"placeholder": "{Employee}",
"text": "John Smith",
"subvariables": [
{
"placeholder": "{Employee.Title}",
"text": "Senior Developer"
},
{
"placeholder": "{Employee.Email}",
"text": "john.smith@company.com"
}
]
}

Variable Stack (Repeating Content)

{
"name": "Projects",
"placeholder": "{Projects}",
"variableStack": {
"0": {
"text": "Project Alpha",
"subvariables": [
{
"placeholder": "{Projects.Status}",
"text": "In Progress"
}
]
},
"1": {
"text": "Project Beta",
"subvariables": [
{
"placeholder": "{Projects.Status}",
"text": "Completed"
}
]
}
}
}

Request Fields

FieldTypeRequiredDescription
templateIdstringYesTemplate ID from upload or selection
namestringYesName for the generated deliverable
descriptionstringNoDescription of the deliverable
variables[]arrayYesArray of variable definitions and values
variables[].namestringYesVariable display name
variables[].placeholderstringYesPlaceholder text in template (e.g., "{Name}")
variables[].textstringYesActual value to replace placeholder
variables[].mimeTypestringYesContent type ("text", "html", etc.)
variables[].allowRichTextInjectionnumberNoAllow HTML/rich text (0 or 1)
variables[].subvariablesarrayNoNested variables within this variable
variables[].variableStackobjectNoMultiple instances for repeating content
variables[].aiPromptstringNoAI prompt for content generation
variables[].metadataobjectNoCustom metadata for the variable
tagsarrayNoTags for categorization
fontsstringNoJSON string of font usage statistics
defaultFontstringNoDefault font for the document
replaceFontsbooleanNoWhether to replace fonts during generation
metadataobjectNoAdditional metadata (sessions, tracking, etc.)

Step 2: Download Generated File

After generating a deliverable, you'll need to download the actual file.

Endpoint

GET https://api.turbodocx.com/deliverable/file/{deliverableId}

Headers

Authorization: Bearer YOUR_API_TOKEN
x-rapiddocx-org-id: YOUR_ORGANIZATION_ID
User-Agent: TurboDocx API Client

Example Request

curl -X GET "https://api.turbodocx.com/deliverable/file/39697685-ca00-43b8-92b8-7722544c574f" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "x-rapiddocx-org-id: YOUR_ORGANIZATION_ID" \
-H "User-Agent: TurboDocx API Client" \
--output "employee-contract-john-smith.docx"

Response

Returns the binary content of the generated document with appropriate content-type headers:

Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Disposition: attachment; filename="employee-contract-john-smith.docx"
Content-Length: 287456

Code Examples

Loading code examples...

Best Practices

Security

  • Never expose API tokens: Store tokens securely in environment variables
  • Use HTTPS only: All API calls must use HTTPS in production
  • Validate file uploads: Check file types and sizes before upload
  • Sanitize variables: Validate variable content to prevent injection attacks

Error Handling

  • Check HTTP status codes: Always verify response status before processing
  • Handle file upload failures: Implement retry logic for large file uploads
  • Validate template variables: Ensure all required variables are provided
  • Log API responses: Keep detailed logs for debugging and monitoring

Performance

  • Optimize file uploads: Compress .docx/.pptx files when possible
  • Cache template details: Store frequently used template information
  • Batch variable processing: Group related variables together
  • Async processing: Use webhooks for long-running document generation

Template Preparation

  • Use clear placeholders: Name variables descriptively (e.g., {CompanyName} not {CN})
  • Consistent formatting: Use consistent placeholder formats throughout templates
  • Test variable extraction: Verify automatic variable detection works correctly
  • Document structure: Organize templates logically with folders and tags

Variable Management

  • Hierarchical organization: Use subvariables for related data
  • Stack for repetition: Use variableStack for lists and repeating sections
  • Rich text sparingly: Only enable rich text injection when formatting is needed
  • AI prompts: Provide clear, specific prompts for AI-generated content

Error Handling & Troubleshooting

Common HTTP Status Codes

Status CodeDescriptionSolution
200SuccessRequest completed successfully
400Bad RequestCheck request body format and required fields
401UnauthorizedVerify API token and headers
403ForbiddenCheck organization ID and permissions
404Not FoundVerify template ID and endpoint URLs
413Payload Too LargeReduce file size or compress template
422Unprocessable EntityValidate field values and constraints
429Too Many RequestsImplement rate limiting and retry logic
500Internal Server ErrorContact support if persistent

Common Issues

Template Upload Failures

Symptoms: Upload returns error or times out

Solutions:

  • Verify file is .docx or .pptx format
  • Check file size is under the maximum limit (typically 25MB)
  • Ensure file is not corrupted or password-protected
  • Verify network connection and try again

Variable Extraction Issues

Symptoms: Variables not detected automatically

Solutions:

  • Use consistent placeholder format: {VariableName}
  • Avoid special characters in placeholder names
  • Ensure placeholders are in main document content (not headers/footers)
  • Check that placeholders are properly formatted text (not images)

Template Selection Problems

Symptoms: Templates not appearing in browse results

Solutions:

  • Verify organization ID matches your account
  • Check that templates are active and not archived
  • Use correct API endpoint for browsing vs. folder contents
  • Verify search parameters and filters

Document Generation Failures

Symptoms: Deliverable generation fails or produces incorrect output

Solutions:

  • Validate all required variables have values
  • Check variable names match template placeholders exactly
  • Ensure subvariable structure matches template expectations
  • Verify file permissions and storage availability

Font and Formatting Issues

Symptoms: Generated documents have incorrect fonts or formatting

Solutions:

  • Use replaceFonts: true to normalize font usage
  • Specify defaultFont for consistent appearance
  • Check that rich text injection is enabled only when needed
  • Validate HTML content in rich text variables

Debugging Tips

  1. Test with simple templates: Start with basic templates before adding complexity
  2. Validate JSON payloads: Use JSON validators before sending requests
  3. Check file encoding: Ensure .docx/.pptx files are not corrupted
  4. Monitor API quotas: Track usage to avoid rate limiting
  5. Use development endpoints: Test with development environment first

Next Steps

Advanced Features to Explore

Now that you've mastered the basics, consider exploring these advanced capabilities:

📖 AI-Powered Content Generation → 📖 Webhook Integration for Status Updates → 📖 Bulk Document Generation → 📖 Template Version Management →

Support

Need help with your template integration? We've got you covered:


Ready to become a template automation wizard? Choose your path (upload new or select existing) and start generating beautiful documents programmatically! 🎯